<template>
  <div class="search-container">
    <van-sticky>
       <form action="/">
          <van-search
            v-model.trim="searchValue"
            show-action
            placeholder="请输入搜索关键词"
            @search="onSearch"
            @cancel="$router.back()"
            background="#3296fa"
            @focus="isShowResult = false"
          />
        </form>
    </van-sticky>

    <keep-alive>
      <searchHistory @clear='history=[]' @search ="onSearch" :history='history' v-if="!searchValue"></searchHistory>
      <searchSuggest :searchText='searchValue' v-else-if='!isShowResult' @clickSearchSuggest="onSearch"></searchSuggest>
      <searchResult  v-else :searchText='searchValue'></searchResult>
    </keep-alive>
  </div>
</template>

<script>
import searchResult from './components/searchResult.vue'
import searchSuggest from './components/searchSuggest.vue'
import searchHistory from './components/searchHistory.vue'
import { setItem, getItem } from '@/utils/storage.js'
export default {
  data () {
    return {
      searchValue: '',
      isShowResult: false,
      history: getItem('TOUTIAO-SEARCHHISTORY') || []
    }
  },
  methods: {
    // 敲击回车 或 点击搜索建议项
    onSearch (val) {
      // console.log('搜索')
      this.history.unshift(val)
      this.history = [...new Set(this.history)]
      this.searchValue = val
      this.isShowResult = true
    }
  },
  components: {
    searchResult,
    searchSuggest,
    searchHistory
  },
  watch: {
    history: {
      deep: true,
      handler () {
        setItem('TOUTIAO-SEARCHHISTORY', this.history)
      }
    }
  }
}
</script>

<style scoped lang='less'>
.search-container {
  .van-search__action{
    color: #fff;
  }
}
</style>
